package com.onlinevideo.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

public class BaseServlet_copy extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        invokeActionMethod(action,req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (ServletFileUpload.isMultipartContent(req)) {
            //创建FileItemFactory 工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建用于解析上传数据的工具类 ServletFileUpload
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            try {
                //解析上传的数据 得到每个表单项FileItem
                List<FileItem> list = servletFileUpload.parseRequest(req);
                req.setAttribute("fileList", list);
                //循环判断：每一个表单项是普通文本类型，还是文件类型
                for (int i = 0; i < list.size(); i++) {
                    FileItem fileItem = list.get(i);
                    if ("action".equals(fileItem.getFieldName())) {
                        String action = fileItem.getString("UTF-8");
                        invokeActionMethod(action, req, resp);
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            System.out.println("非文件上传不能用post方法");
        }
//        doGet(req, resp);
    }
    protected void invokeActionMethod(String action, HttpServletRequest req, HttpServletResponse resp) {
        //根据action值，判断需要调用哪个方法，方法名和action值同名
        try {
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, req, resp);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
